package com.atguigu.gmall.pay.api;


import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RequestMapping("/api/payment")
@RestController
public class PayController {

    @Autowired
    PayService payService;

    @Autowired
    OrderFeignClient orderFeignClient;


    /**
     * 去支付宝查询一个订单是否支付了
     * 1: 支付成功
     * 0: 其他状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("/status/{outTradeNo}")
    public String queryOrderPayStatus(@PathVariable("outTradeNo") String outTradeNo) throws JsonProcessingException, AlipayApiException {

        Boolean b = payService.queryOrderStatus(outTradeNo);

        return b?"1":"0";
    }


    @GetMapping(value = "/alipay/submit/{orderId}",produces = "text/html")
    public String payment(@PathVariable("orderId") Long orderId) throws Exception {
        PayParamVo paramVo = new PayParamVo();

        OrderInfo orderById = orderFeignClient.getOrderById(orderId);
        paramVo.setTotal_amount(orderById.getTotalAmount().toString());
        paramVo.setOut_trade_no(orderById.getOutTradeNo());
        paramVo.setSubject(orderById.getConsignee()+"的订单");
        Date expireTime = orderById.getExpireTime();
        //设置订单的过期时间, 支付宝的自动收单，支付宝订单过期时间就是我们数据库中保存订单过期时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramVo.setTime_expire(format.format(expireTime));
        paramVo.setBody(orderById.getOrderComment());
        //调用支付 返回支付页面
        String result = payService.payOrder(paramVo);

        return result;

    }
}
